package com.tuyue.police.weixin.handler;

import com.tuyue.police.dao.IUserDao;
import com.tuyue.police.pojo.User;
import com.tuyue.police.weixin.bean.UrlBean;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.MenuButtonType;

/**
 * 菜单拦截器
 *
 * @author Binary Wang(https://github.com/binarywang)
 */
@Component
@Slf4j
public class MenuHandler extends AbstractHandler {

    @Autowired
    private IUserDao userDao;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        log.info("msg:{}", String.format("type:%s, event:%s, key:%s", wxMessage.getMsgType(), wxMessage.getEvent(), wxMessage.getEventKey()));
        String msg = "";
        if (MenuButtonType.VIEW.equals(wxMessage.getEvent())) {
            return null;
        }
        String fromUser = wxMessage.getFromUser();
        log.error("用戶的openid:"+fromUser);
        User user = userDao.findByUserOpenId(fromUser);
        switch (wxMessage.getEventKey()) {
            case "31":
                StringBuffer sb = new StringBuffer();
                if (ObjectUtils.isEmpty(user)) {
                    log.info("点击了31" + msg);
                    sb.append("<a href=\"");
                    sb.append(UrlBean.AUTHORIZEURL+UrlBean.BDZC);
                    sb.append("\">绑定注册</a>");
                    log.info(sb.toString());
                }else {
                    sb.append("您已经绑定账号：");
                    sb.append(user.getUserName());
                }
                msg = sb.toString();
                break;
            case "32":
                // TODO: 2018/3/23
                log.info("点击了32" + msg);
                msg = "点击了32";
                break;
            default:
                log.info("点击了其他" + msg);
        }

        return WxMpXmlOutMessage.TEXT().content(msg)
                .fromUser(wxMessage.getToUser()).toUser(wxMessage.getFromUser())
                .build();
    }

}
